package cn.itcast.web.controller.cargo;


import cn.itcast.domain.cargo.*;
import cn.itcast.service.cargo.*;
import cn.itcast.web.controller.BaseController;
import cn.itcast.web.utils.DownloadUtil;
import cn.itcast.web.utils.FileUploadUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import com.github.pagehelper.PageInfo;
import com.sun.corba.se.spi.ior.IdentifiableFactory;
import net.sf.jasperreports.engine.JREmptyDataSource;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.sql.DataSource;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Controller
@RequestMapping("/cargo/invoice")
public class InvoiceController extends BaseController {

    @Autowired
    private DataSource dataSource;

    @Reference
    private ExportService exportService;

    @Reference
    private PackingService packingService;

    @Reference
    private ShippingService shippingService;

    @Reference
    private ContractService contractService;

    @Reference
    private InvoiceService invoiceService;

    @Autowired
    private FileUploadUtil fileUploadUtil;


    //分页查询
    @RequestMapping("/list")
    public String list(@RequestParam(defaultValue = "1") int pageNum, @RequestParam(defaultValue = "5") int pageSize){
        InvoiceExample invoiceExample = new InvoiceExample();
        invoiceExample.createCriteria();
        PageInfo<Invoice> pageInfo = invoiceService.findByPage(invoiceExample, pageNum, pageSize);
        request.setAttribute("pageInfo",pageInfo);

        return "cargo/invoice/invoice-list";
    }


    //跳转到发票添加
    @RequestMapping("/toInvoice")
    public String toInvoice(String shippingOrderId){


        IncasementProxy incasementProxy = shippingService.findById(shippingOrderId);
        if (incasementProxy.getState()==1){

            return "cargo/invoice/invoice-fail";

        }

        //用于贸易条款拼接
        StringBuilder stringBuilder = new StringBuilder();

        // 通过委托单id=装箱id  获取 装箱对象
        Incasement incasement = packingService.findIncasementById(shippingOrderId);

        //=====报运合同号======
        String exportNos = incasement.getExportNos();


        //=======发票金额(报运金+装箱金+委托金)========

        //报运金==全部购销合同总金额
        double exportAllMoney = 0;

        //所有的运单号
        String exportIds = incasement.getExportIds();

        String[] exportNoArray = exportIds.split(",");

        //遍历所有的报运单---获取购销合同号---获取购销合同总金额
        for (int i = 0; i < exportNoArray.length; i++) {

            //获取报运单对象
            Export export = exportService.findById(exportNoArray[i].replace("[","").replace("]",""));

            //获取所有的购销合同id
            String contractIds = export.getContractIds();
            String[] contractIdArray = contractIds.split(",");

            //遍历所有的购销合同--获取购销合同总价
            for (int k = 0; k < contractIdArray.length; k++) {
                Contract contract = contractService.findById(contractIdArray[i]);
                //计算全部购销合同的价格
                exportAllMoney += contract.getTotalAmount();

                //贸易条款 字符串拼接
                String tradeTerms = contract.getTradeTerms();
                if (i == exportNoArray.length-1){
                    stringBuilder.append(tradeTerms);
                }else {
                    stringBuilder.append(tradeTerms).append(",");
                }

            }
        }


        //装箱运金
        double packingMoney = incasement.getPackingMoney();

        //委托金
        double proxyMoney = 0;

        //====发票金额====
        double invoiceMoney =  exportAllMoney + packingMoney + proxyMoney;

        //====贸易条款====
        String allTradeTerms = stringBuilder.toString();


        request.setAttribute("exportNos",exportNos);
        request.setAttribute("invoiceMoney",invoiceMoney);
        request.setAttribute("allTradeTerms",allTradeTerms);

        request.setAttribute("shippingOrderId",shippingOrderId);

        return "cargo/invoice/invoice-add";
    }


    //添加发票
    @RequestMapping("/edit")
    public String add(Invoice invoice, MultipartFile Photo) throws Exception {

        //文件上传
        if (Photo!=null){
            String url = fileUploadUtil.upload(Photo); //返回的就是上传图片到地址
            invoice.setPickupPhoto("http://"+url); //路径并没有存储http的，所以前面添加http
            System.out.println(invoice.getPickupPhoto());
        }

        //if(contractProduct.getId()==null||contractProduct.getId().equals("")){
        if(StringUtils.isEmpty(invoice.getInvoiceId())){
            //没有带id过来 , 新增操作

            //补全创建人与创建人所属部门
            invoice.setCreateBy(getLoginUser().getId());  //登陆者的id
            invoice.setCreateDept(getLoginUser().getDeptId());  //登陆者所属的购销合同
            invoice.setCreateTime(new Date());
            invoice.setUpdateBy(getLoginUser().getId());
            invoice.setUpdateTime(new Date());

            invoiceService.save(invoice);
        }else{
            //更新   update xx set xx=xx  xx=xx where id = xx  更新是一定要带着id过来

            invoice.setUpdateBy(getLoginUser().getId());
            invoice.setUpdateTime(new Date());

            invoiceService.update(invoice);
        }

        //获取委托单.
        IncasementProxy incasementProxy = shippingService.findById(invoice.getShippingOrderId());
        //修改委托单状态
        incasementProxy.setState(1);
        shippingService.updateState(incasementProxy.getShippindOrderId(),incasementProxy.getState());

        return "redirect:/cargo/invoice/list.do";
    }


    //删除发票
    @RequestMapping("/delete")
    @ResponseBody
    public Map<String,Object> delete(String invoiceId){

        Map<String, Object> resultMap = new HashMap<>();

        //获取发票对象
        Invoice invoice = invoiceService.findById(invoiceId);
        //判断发票对象是否为草稿状态
        if (invoice.getStatus().equals("0")){ //草稿状态
            invoiceService.delete(invoiceId);
            resultMap.put("message", "删除成功");
        }else { //删除失败
            resultMap.put("message", "删除失败，只有草稿状态才能删除!!!");
        }

        return resultMap;

    }

    @RequestMapping("/printExcel")
    public void printExcel(String inputDate) throws IOException {

        //1.创建工作簿
        Workbook wb = new XSSFWorkbook();


        //2.生成工作单
        Sheet sheet = wb.createSheet("发票表");
        //设置合并列
        /**
         * 参数依次为： 开始行号，结束行号，开始列号，结束列号
         */
        sheet.addMergedRegion(new CellRangeAddress(0,0,1,8));
        //设置列宽， 参数为：列索引，列宽度值
        sheet.setColumnWidth(0,6*256);
        sheet.setColumnWidth(1,21*256);
        sheet.setColumnWidth(2,16*256);
        sheet.setColumnWidth(3,29*256);
        sheet.setColumnWidth(4,11*256);
        sheet.setColumnWidth(5,11*256);
        sheet.setColumnWidth(6,11*256);
        sheet.setColumnWidth(7,11*256);
        sheet.setColumnWidth(8,11*256);
        sheet.setColumnWidth(9,11*256);

        //3.创建表头行
        Row row = sheet.createRow(0);
        //3.4.设置行高度
        row.setHeightInPoints(36);

        //inputDate: 2019-10 或 2019-08
        //3.1 设置标题
        String title = "发票表";
        //3.2 设置第二列的内容作为标题
        Cell cell = row.createCell(1);
        cell.setCellValue(title);
        //3.3 设置大标题样式
        cell.setCellStyle(bigTitle(wb));


        //4.创建内容行
        //4.1 创建标题
        row = sheet.createRow(1);

        String[] titles = {"发票号","报运合同号","贸易条款","发票金额","发票时间","发票状态"};
        for(int i=0;i<titles.length;i++){
            cell = row.createCell(i + 1);
            cell.setCellValue(titles[i]);
            //设置样式
            cell.setCellStyle(title(wb));
        }

        //4.2 内容
        //查询数据库获取内容
        int index = 2;

        InvoiceExample invoiceExample = new InvoiceExample();
        invoiceExample.createCriteria();
        List<Invoice> invoiceList = invoiceService.findAll(invoiceExample);


        if(invoiceList!=null){
            for(Invoice invoice:invoiceList){


                //创建行
                row = sheet.createRow(index++);


                //设置行高
                row.setHeightInPoints(24);

                //设置列内容


                //客户列
                cell = row.createCell(1);


                if(invoice.getInvoiceId()!=null) {

                    //样式
                    cell.setCellStyle(text(wb));
                    //内容
                    cell.setCellValue(invoice.getInvoiceId());
                }

                //订单列
                cell = row.createCell(2);
                if(invoice.getScNo()!=null) {

                    //样式
                    cell.setCellStyle(text(wb));
                    //内容
                    cell.setCellValue(invoice.getScNo());
                }
                //货号列
                cell = row.createCell(3);
                if(invoice.getTradeTerms()!=null) {

                    //样式
                    cell.setCellStyle(text(wb));
                    //内容
                    cell.setCellValue(invoice.getTradeTerms());
                }

                //数量列
                cell = row.createCell(4);


                //样式
                cell.setCellStyle(text(wb));
                //内容
                cell.setCellValue(invoice.getInvoiceMoney());


                //工厂列
                cell = row.createCell(5);


                //样式
                cell.setCellStyle(text(wb));
                //内容
                cell.setCellValue(invoice.getInvoiceTime());


                //交期列
                cell = row.createCell(6);


                //样式
                cell.setCellStyle(text(wb));
                //内容
                cell.setCellValue(invoice.getStatus());





            }

        }

        //3.把工作簿写出到浏览器响应（给用户下载Excel)

  /*  //3.2. 设置写出的文件格式： excel格式
    response.setContentType("application/octet-stream;charset=utf-8");
    //3.2 提示浏览器一个下载的文件名称: Content-Disposition
    response.addHeader("Content-Disposition","attachment;filename=product.xlsx");

    OutputStream outputStream = response.getOutputStream();

    //3.3 把工作簿写出到响应中
    wb.write(outputStream);
    outputStream.flush();*/

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        wb.write(outputStream);
        new DownloadUtil().download(outputStream,response,"发票表.xlsx");
    }


    //大标题的样式
    public CellStyle bigTitle(Workbook wb){
        CellStyle style = wb.createCellStyle();
        Font font = wb.createFont();
        font.setFontName("宋体");
        font.setFontHeightInPoints((short)16);
        font.setBold(true);//字体加粗
        style.setFont(font);
        style.setAlignment(HorizontalAlignment.CENTER);             //横向居中
        style.setVerticalAlignment(VerticalAlignment.CENTER);     //纵向居中
        return style;
    }

    //小标题的样式
    public CellStyle title(Workbook wb){
        CellStyle style = wb.createCellStyle();
        Font font = wb.createFont();
        font.setFontName("黑体");
        font.setFontHeightInPoints((short)12);
        style.setFont(font);
        style.setAlignment(HorizontalAlignment.CENTER);             //横向居中
        style.setVerticalAlignment(VerticalAlignment.CENTER);     //纵向居中
        style.setBorderTop(BorderStyle.THIN);                 //上细线
        style.setBorderBottom(BorderStyle.THIN);               //下细线
        style.setBorderLeft(BorderStyle.THIN);                //左细线
        style.setBorderRight(BorderStyle.THIN);                   //右细线
        return style;
    }

    //文字样式
    public CellStyle text(Workbook wb){
        CellStyle style = wb.createCellStyle();
        Font font = wb.createFont();
        font.setFontName("Times New Roman");
        font.setFontHeightInPoints((short)10);

        style.setFont(font);

        style.setAlignment(HorizontalAlignment.LEFT);           //横向居左
        style.setVerticalAlignment(VerticalAlignment.CENTER);     //纵向居中
        style.setBorderTop(BorderStyle.THIN);                 //上细线
        style.setBorderBottom(BorderStyle.THIN);               //下细线
        style.setBorderLeft(BorderStyle.THIN);                //左细线
        style.setBorderRight(BorderStyle.THIN);                   //右细线

        return style;
    }

    @RequestMapping("/printPDF")
    @ResponseBody
    public  void exportPdf(String id) throws Exception {
        //通知浏览器以文件下载的方式处理内容
        String  fileName = "发票单.pdf";
        fileName =  URLEncoder.encode(fileName,"utf-8");

        //1. 找到模板的输入流
        InputStream inputStream = session.getServletContext().getResourceAsStream("/jasper/invoice.jasper");

        Invoice invoice=invoiceService.findById(id);

        Map<String,Object> map=new HashMap<>();

        if ( invoice.getInvoiceId().replace("[","").replace("]","") != null){
            map.put("invoiceId", invoice.getInvoiceId());
        }else {
            map.put("invoiceId","无");
        }

        if ( invoice.getInvoiceTime() != null){
            map.put("invoiceTime", invoice.getInvoiceTime());
        }else {
            map.put("invoiceTime","无");
        }

        if ( invoice.getScNo().replace("[","").replace("]","") != null){
            map.put("scNo",  invoice.getScNo());
        }else {
            map.put("scNo","无");
        }

        if ( invoice.getTradeTerms() != null){
            map.put("tradeTerms", invoice.getTradeTerms());
        }else {
            map.put("tradeTerms","无");
        }

        if ( invoice.getInvoiceMoney() != null){
            map.put("invoiceMoney",  invoice.getInvoiceMoney());
        }else {
            map.put("invoiceMoney","无");
        }

        JasperPrint jasperPrint = JasperFillManager.fillReport(inputStream, map, new JREmptyDataSource());
        response.setContentType("application/pdf;charset=utf-8");
        response.setHeader("content-disposition","attachment;filename="+fileName);
        //3. 把pdf输出
        JasperExportManager.exportReportToPdfStream(jasperPrint,response.getOutputStream());
    }

}
